package cn.id68.www.http.request;

import java.util.Map;

import cn.id68.www.http.RequestCall;
import cn.id68.www.http.callback.Callback;
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.internal.framed.Header;

/**
 * Created by Administrator on 2017/3/20.
 */
public abstract class OkHttpRequest {

    protected String url;
    protected Object tag;
    protected Map<String, String> params;
    protected Map<String, String> headers;
    protected int id;

    protected Request.Builder builder = new Request.Builder();

    public OkHttpRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, int id) {
        this.url = url;
        this.tag = tag;
        this.params = params;
        this.headers = headers;
        this.id = id;

        if (url == null){
            throw new NullPointerException("NUll");
        }
        initBuilder();
    }

    private void initBuilder() {
        builder.url(url).tag(tag);
        appendHeaders();
    }

    protected void appendHeaders() {
        Headers.Builder headersBuilder = new Headers.Builder();
        if (headers == null || headers.isEmpty()){
            return;
        }
        for (String key:headers.keySet()){
            headersBuilder.add(key,headers.get(key));
        }

        builder.headers(headersBuilder.build());
    }


    public RequestCall build(){
        return new RequestCall(this);
    }

    public int getId() {
        return id;
    }

    protected abstract RequestBody buildRequestBody();

    protected RequestBody wraRequestBody(RequestBody requestBody,final Callback callback){
        return requestBody;
    }

    protected abstract Request buildRequest(RequestBody requestBody);


    public  Request generateRequest(Callback callback){
        RequestBody requestBody = buildRequestBody();
        RequestBody wrRequestBody = wraRequestBody(requestBody,callback);
        Request request = buildRequest(wrRequestBody);
        return request;
    }
}
